<template>
  <div class="class-page">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <div class="secondary-filters">
        <span 
          :class="{ active: currentStatus === 'all' }" 
          @click="setStatus('all')">全部</span>
        <span 
          :class="{ active: currentStatus === 'ongoing' }" 
          @click="setStatus('ongoing')">进行中</span>
        <span 
          :class="{ active: currentStatus === 'finished' }" 
          @click="setStatus('finished')">已结束</span>

        <div class="search-join">
          <input v-model="searchQuery" style="border-radius:20px" type="text" placeholder="搜索课堂" class="search-input" />
          <img style="margin-right:80px" src="@/assets/picture/find.png" alt="搜索" class="search-icon" @click="searchClass" />
          <button class="join-class-btn" @click="showModal = true">加入课堂</button>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <div v-if="showModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <h2>加入课堂</h2>
        <form @submit.prevent="submitJoinClass">
          <div class="form-group">
            <label for="class-code">课堂邀请码</label>
            <input type="text" id="class-code" v-model="joinClassCode" required />
            <p style="font-size:14px;color:gray">（向授课教师获取8位课堂邀请码）</p>
          </div>
          <div class="form-actions">
            <button type="submit" class="submit-btn">提交</button>
            <button type="button" class="cancel-btn" @click="closeModal">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="class-list">
      <div v-if="filteredClasses.length === 0" class="no-results">没有找到任何课程。</div>
      <div 
        class="class-card"
        v-for="classItem in paginatedClasses" 
        :key="classItem.semester_id" 
        @click="goToClassManagement(classItem.semester_id)">
        <h4 style="margin:20px 0px 10px 0px;color:#646464;font-size:14px ">{{ classItem.semester_name }}</h4> 
        <img :src="classItem.cover || defaultCover" alt="教师头像" class="teacher-avatar" />
        <p style="font-size:14px" class="teacher-name">{{ classItem.username }}</p>
        <div class="progress-wrapper">
        <div class="progress-bar">
          <div
            class="progress-inner"
            :style="{ width: progressPercent(classItem) }">
          </div>
        </div>

        <!-- 右侧文字 / √ -->
        <span class="progress-text">
          <template v-if="classItem.watched_cnt === classItem.total_cnt">
            <img src="@/assets/picture/check.png" class="done-icon" />
          </template>
          <template v-else>
            {{ classItem.watched_cnt }} / {{ classItem.total_cnt }}
          </template>
        </span>
      </div>
        <div class="class-info">
          <div class="info-item">
            <img src="@/assets/picture/people.png" alt="课堂人数" class="info-icon" />
            <span style="font-size:12px">{{ classItem.stu_cnt }}</span>
          </div>
          <div class="info-item">
            <img src="@/assets/picture/homework.png" alt="作业数量" class="info-icon" />
            <span style="font-size:12px">{{ classItem.hmk_cnt }}</span>
          </div>
          <button class="status-btn" :class="{ 'ongoing-btn': classItem.semester_status === '进行中', 'finished-btn': classItem.semester_status === '已结束' }">
            {{ classItem.semester_status }}
          </button>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <PagiNation class="pagination"
      :currentPage="currentPage"
      :totalPages="totalPages"
      @page-change="handlePageChange"
    />

    <!-- 加载指示器 -->
    <div v-if="isLoading" class="loading">加载中...</div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import PagiNation from '@/components/PagiNation.vue'; // 引入分页组件
import { getStudentClasses, joinClass } from '@/services/api';

export default {
  name: 'ClassPage',
  components: {
    PagiNation, // 注册分页组件
  },
  setup() {
    const router = useRouter();
    const searchQuery = ref('');
    const currentStatus = ref('all');
    const currentPage = ref(1);
    const itemsPerPage = 8; // 定义为常量
    const classes = ref([]);
    const techId = ref(null);
    const token = ref(null);
    const showModal = ref(false);
    const isLoading = ref(false); // 添加加载状态
    const joinClassCode = ref('');

    const goToClassManagement = (classId) => {
       localStorage.setItem('selectedClassId', classId);
      router.push(`/student-management/${classId}/StuNoti`);
    };

    const closeModal = () => {
      showModal.value = false;
    };

      const submitJoinClass = () => {
      if (!joinClassCode.value) {
        ElMessage.error('请输入课堂邀请码');
        return;
      }

      isLoading.value = true;
      joinClass({ 
        class_code: joinClassCode.value,
        stu_id: localStorage.getItem('id') // 学生ID
      })
        .then(response => {
          if (response.data.status === 1) {
            ElMessage.success('成功加入课堂');
            fetchClasses();
            closeModal();
          }else if(response.data.status === 0){
            ElMessage.error((response.data.msg || '无效的邀请码'));
          }
        })
        .catch(error => {
          ElMessage.error('加入课堂失败：' + (error.response?.data.msg || '无效的邀请码'));
        })
        .finally(() => {
          isLoading.value = false;
        });
    };

    const setStatus = (status) => {
      currentStatus.value = status;
      currentPage.value = 1; // 重置页码
      fetchClasses();
    };

    const searchClass = () => {
      currentPage.value = 1; // 重置为第一页
      fetchClasses();
    };
    const progressPercent = (c) =>
      c.total_cnt ? `${Math.round((c.watched_cnt / c.total_cnt) * 100)}%` : '0%';

    const fetchClasses = () => {
      const studentId = localStorage.getItem('id');
      if (!studentId) {
        router.push('/login');
        return;
      }

      isLoading.value = true;
      
      // 转换状态值为接口需要的数值格式
      const statusMap = {
        all: 0,
        ongoing: 1,
        finished: 2
      };

      getStudentClasses(studentId, statusMap[currentStatus.value])
        .then(response => {
          if (response.data.status === 1) {
            classes.value = response.data.data.map(item => ({
              semester_id: item.semester_id,
              semester_name: item.semester_name,
              username: item.username,
              stu_cnt: item.stu_cnt,
              hmk_cnt: item.hmk_cnt,
              semester_status: item.semester_status|| 0,
              cover: item.cover, // 使用接口返回的cover字段
              watched_cnt: item.watched_cnt, 
              total_cnt: item.total_cnt
            }));
          }
        })
        .catch(error => {
          console.error('请求错误:', error);
          classes.value = [];
        })
        .finally(() => {
          isLoading.value = false;
        });
    };

    const filteredClasses = computed(() => {
      let filtered = classes.value || [];  // 确保 classes.value 是数组

      if (currentStatus.value !== 'all') {
        filtered = filtered.filter(classItem =>
          (currentStatus.value === 'ongoing' && classItem.semester_status === '进行中') ||
          (currentStatus.value === 'finished' && classItem.semester_status === '已结束')
        );
      }

      if (searchQuery.value) {
        filtered = filtered.filter(classItem =>
          classItem.semester_name.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
      }

      console.log('筛选后的课程:', filtered);
      return filtered;
    });

    const paginatedClasses = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredClasses.value.slice(start, end) || [];  // 确保返回数组
    });

    const totalPages = computed(() => {
      const pages = Math.ceil(filteredClasses.value.length / itemsPerPage) || 1;  // 默认至少一页
      return pages;
    });

    const handlePageChange = (newPage) => {
      currentPage.value = newPage; // 更新当前页码
    };

    onMounted(() => {
      const storedTechId = localStorage.getItem('id');
      const storedToken = localStorage.getItem('token');

      if (storedTechId && storedToken) {
        techId.value = storedTechId;
        token.value = storedToken;
        fetchClasses();
      } else {
        console.error('登录信息缺失，重定向到登录页面');
        router.push('/login');
      }
    });

    return {
      searchQuery,
      currentStatus,
      currentPage,
      classes,
      itemsPerPage,
      showModal,
      paginatedClasses,
      totalPages,
      goToClassManagement,
      searchClass,
      setStatus,
      closeModal,
      filteredClasses,
      handlePageChange,
      isLoading, // 返回加载状态
      joinClassCode,
      submitJoinClass,
      progressPercent
    };
  },
};
</script>



<style scoped>
/* 进度条整体 */
.progress-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px 8px;
  margin-top: 6px;
}

/* 灰底条 */
.progress-bar {
  flex: 1;
  height: 6px;
  background: #e0e0e0;
  border-radius: 3px;
  overflow: hidden;
  margin-right: 8px;
}
.pagination {
      margin-top: 20px;
    text-align: center;
    display: flex
;
    justify-content: center;
    align-items: center;
    position: absolute;
    bottom: 0;
    left: 50%;
}

/* 彩色进度 */
.progress-inner {
  height: 100%;
  background: linear-gradient(90deg, #45a0ff, #4caf50);
  transition: width 0.3s;
}

/* 右侧文本 / √ */
.progress-text {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}
.done-icon {
  width: 16px;
  vertical-align: middle;
}
.class-page {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.secondary-filters {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  color: #333;
}

.secondary-filters span {
  margin-right: 20px;
  cursor: pointer;
  font-weight: normal;
  padding-bottom: 10px;
  width: 7%;
  text-align: center;
}

.secondary-filters span.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
  margin-bottom: -2px;
}

.search-join {
  margin-left: auto;
  display: flex;
  align-items: center;
  white-space: nowrap;
  position: relative;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 20px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px;
}

.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}

.join-class-btn {
  margin-left: 10px;
  padding: 8px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;  
  background-color: #125AA2;
  color: #fff;
}

.join-class-btn:hover {
  background-color: #3987d4;
}

.class-list {
  display: grid;
  grid-template-columns: repeat(4, minmax(200px, 1fr));
  gap: 20px;
}

.class-card {
  position: relative;
  border: 1px solid #ccc;
  border-radius: 8px;
  text-align: center;
  transition: transform 0.2s;
  cursor: pointer;
  background-color: #fff;
}

.class-card:hover {
  transform: scale(1.05);
}

.teacher-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.teacher-name {
  color: rgb(112, 112, 112);
  margin: 5px  0px 20px 0px;
}

.class-info {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 0px 10px;
}

.info-icon {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}

.status-btn {
  border: none;
  border-radius: 20px;
  padding: 3px 8px;
  color: white;
  cursor: default;
  width: 70px;
  margin-left: 10px;
  font-size: 12px;
}

.ongoing-btn {
  background-color: #4caf50;
}

.finished-btn {
  background-color: #a1a1a1;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s;
}

.modal-content {
  background-color: #fff;
  padding: 30px;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
  position: relative;
  animation: slideIn 0.3s;
}

.modal-content h2 {
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.modal-content .form-group {
  margin-bottom: 15px;
}

.modal-content label {
  display: block;
  margin-bottom: 5px;
  color: #555;
}

.modal-content input[type="text"],
.modal-content input[type="date"],
.modal-content input[type="file"] {
  width: 90%;
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.submit-btn,
.cancel-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  background-color: #125AA2;
  color: #fff;
  margin-right: 10px;
}

.submit-btn:hover {
  background-color: #3987d4;
}

.cancel-btn {
  background-color: #ccc;
  color: #333;
}

.cancel-btn:hover {
  background-color: #999;
}

/* 加载指示器 */
.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  color: #125AA2;
}

/* 无结果提示 */
.no-results {
  text-align: center;
  color: #666;
  font-size: 16px;
  margin-top: 50px;
}

/* 弹窗动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideIn {
  from { transform: translateY(-20px); }
  to { transform: translateY(0); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .class-list {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}

@media (max-width: 480px) {
  .register-page {
    padding: 20px;
    margin: 30px 10px;
  }

  .secondary-filters span {
    margin-right: 10px;
    font-size: 14px;
  }

  .search-input {
    min-width: 150px;
  }

  .join-class-btn {
    padding: 6px 8px;
    font-size: 14px;
  }

  .modal-content {
    padding: 20px;
  }

  .modal-content h2 {
    font-size: 20px;
  }
}
</style>
